import base64
import ssl
import json
import websocket

from .base import Client, get_lcu_auth


class WsLolClient(Client):
    """
    LCU WebSocket Client
    """
    def __init__(self):
        port, token = get_lcu_auth()
        self.port = port
        self.token = token
        # riot:{token} 会被 websocket-client 自动转换成 Basic Auth
        self.base_url = f"wss://127.0.0.1:{port}/"
        super().__init__(port, token, self.base_url)
        self.ws = None

    def connect(self):
        # 构造 Basic Auth
        auth = base64.b64encode(f"riot:{self.token}".encode()).decode()
        headers = [f"Authorization: Basic {auth}"]

        self.ws = websocket.WebSocketApp(
            self.base_url,
            header=headers,
            on_open=self.on_open,
            on_message=self.on_message,
            on_error=self.on_error,
            on_close=self.on_close
        )

        # run_forever 会阻塞在这里
        self.ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

    def on_open(self, ws):
        print("✅ WebSocket connected")

        # 订阅对局结束事件
        subscribe_msg = [5, "OnJsonApiEvent_lol-end-of-game_v1_end-of-game-stats"]
        ws.send(json.dumps(subscribe_msg))
        print("📡 Subscribed to end-of-game events")

    def on_message(self, ws, message):
        try:
            # 忽略空消息
            if not message or message == "null":
                return

            data = json.loads(message)

            # Riot 协议一般是数组 [eventType, eventName, payload]
            if isinstance(data, list) and len(data) >= 3:
                event_name = data[1]
                payload = data[2]

                if event_name == "OnJsonApiEvent_lol-end-of-game_v1_end-of-game-stats":
                    print("🎮 Game ended! Stats:")
                    print(json.dumps(payload, indent=2, ensure_ascii=False))
            else:
                print("📩 Unhandled message:", data)

        except json.JSONDecodeError:
            print("⚠️ Received non-JSON message:", message)
        except Exception as e:
            print("❌ Error handling message:", e, message)


    def on_error(self, ws, error):
        print("❌ WebSocket error:", error)

    def on_close(self, ws, close_status_code, close_msg):
        print("🔌 WebSocket closed", close_status_code, close_msg)
